# -*- coding: utf-8 -*-
"""Sample model module."""

import logging
log = logging.getLogger(__name__)
import transaction
import time

from sqlalchemy import Table, Column, Integer, String, Boolean, MetaData, ForeignKey, Text
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relation, backref

from crv.model import DeclarativeBase, metadata, DBSession

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# CertStore
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class CertStore(object):
    """
    Certificate Stores
    A certstore is one CA + certs that the CA signed + CRL
    """
    def __init__(self):
        self.caname=""
        self.password=""
        self.doc=""
        self.misc=""

    def __repr__(self):
        return "CertStore(caname=%s, doc=%s, misc=%s, password=%s)" % (self.caname, self.doc, self.misc, self.password)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Certificate
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Certificate(object):
    """
    Certificates
    has many to one relation to CertStore
    Each certificate has a password to store the private key
    """
    def __init__(self):
        self.cn=""
        self.request=""
        self.certificate=""
        self.privatekey=""
        self.password=""

    def __repr__(self):
        return "Certificate(cn=%s)" % (self.cn)



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Database tables
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# CertStore.caname == Certificate.cn ==> this cert is the ca cert of this certstore.

tbCertificate=Table('Certificate',metadata,
               Column('Certificate_ID',Integer,primary_key=True),
               Column('CertStore_ID',Integer,ForeignKey('CertStore.CertStore_ID')),
               Column('cn',String(512),nullable=False),
               Column('request',Text,nullable=False),
               Column('certificate',Text,nullable=False),
               Column('privatekey',Text,nullable=False),
               Column('password',Text,nullable=False),
               )

tbCertStore=Table('CertStore',metadata,
                  Column('CertStore_ID',Integer,primary_key=True),
                  Column('caname',Text, nullable=False),
                  Column('password',Text,nullable=False),
                  Column('doc',Text,nullable=False),
                  Column('misc',Text,nullable=False),
                )


mapper(Certificate, tbCertificate)

mapper(CertStore,tbCertStore,
       properties={
        'certs':relation(Certificate,
                         backref='certstore',cascade="all"),    
        })

